//
//  main.cpp
//  syncer_1_1
//
//  Created by Silvtar on 11/27/12.
//  Copyright (c) 2012 Silvtar. All rights reserved.
//

#include	<sys/types.h>
#include	<sys/wait.h>
#include 	<sys/socket.h>
#include	<netinet/in.h>
#include	<unistd.h>
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<string>
#include	"netio.c"
#include	"FileTree.h"

const std::string loDir = "/home/silvtar/Ubuntu One";

int main(int argc, const char * argv[]) {

	int listenfd;
	int connfd;
	pid_t childpid;
	socklen_t clilen;
	struct sockaddr_in cliaddr;
	struct sockaddr_in servaddr;

	//获得套接字
	if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		printf("socket error!\n");
		return 1;
	}

	//填写地址结构
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY );
	servaddr.sin_port = htons(2012);

	//绑定端口号
	if (bind(listenfd, (sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
		printf("bing port:2012 error!\n");
		return 1;
	}

	//开始监听
	if (listen(listenfd, 5) < 0) {
		printf("listen error!\n");
		return 1;
	}

	while (true) {
		clilen = sizeof(cliaddr);
		printf("waiting for client...\n");
		connfd = accept(listenfd, (sockaddr *) &cliaddr, &clilen);
		childpid = 0;

		//如果是子进程
		if ((childpid = fork()) == 0) {
			printf("%%it's child thread\n");
			char ptr[4096] = "hello, this is server!\n";
			close(listenfd);
			writen(connfd, ptr, 4096);

//			SSTree loTree;
//			loTree.build(loDir);

			/*
			 SSTree* rpTree = (SSTree*)malloc(4096);
			 bzero(ptr, 4096);
			 readn(connfd, ptr, 4096);
			 bcopy(ptr, rpTree, 4096);

			 printf("i will display the filelist\n");
			 rpTree->printFileTree();
			 */

			readn(connfd, ptr, 4096);
			printf("client:%s\n", ptr);
			exit(0);
		}
		//如果是父进程
		else {
			printf("it's father thread,child pid = %d\n", childpid);
		}
		close(connfd);
		int wc;
		wait(&wc);
	}

	return 0;
}

